﻿using System;
using System.Reflection;
using Eto.Parse;

namespace Furesoft.Database
{
    public class SyntaxTree
    {
        public static object Build(Match m)
        {
            foreach (var mm in m.Matches)
            {
                foreach (var mmm in mm.Matches)
                {
                    foreach (var type in Assembly.GetEntryAssembly().GetTypes())
                    {
                        if (type.BaseType != null)
                        {
                            if (type.BaseType.Name == typeof(IAst).Name)
                            {
                                var obj = (IAst)Activator.CreateInstance(type);

                                if (obj.Name == mm.Name)
                                {
                                    var props = type.GetProperties();
                                    for (int i = 0; i < props.Length; i++)
                                    {
                                        if (props[i].PropertyType.BaseType.Name == typeof(IAst).Name)
                                        {
                                            props[i].SetValue(obj, SyntaxTree.Build(mm), null);

                                            continue;
                                        }
                                        else if (props[i].Name == mmm.Name)
                                        {
                                            props[i].SetValue(obj, mmm.StringValue, null);
                                        }
                                    }
                                    return obj;
                                }
                            }
                        }
                    }
                }
            }

            return null;
        }
    }
}